package com.pai4j.pgc.service;
import com.pai4j.common.enums.community.ESEventEnum;
import com.pai4j.common.listener.event.CommunityContentEvent;
import com.pai4j.common.listener.event.data.CommunityEventData;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.pgc.pojo.es.AbstractESMessageDTO;
import com.pai4j.pgc.service.es.CommunityElasticSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class CommunityContentListener implements ApplicationListener<CommunityContentEvent> {

    @Autowired
    private CommunityElasticSearchService communityElasticSearchService;

    @Override
    public void onApplicationEvent(CommunityContentEvent communityContentEvent) {
        Object obj = communityContentEvent.getSource();
        CommunityEventData data = (CommunityEventData) obj;
        if (data.getEvent() == ESEventEnum.CREATE) {
            AbstractESMessageDTO abstractESMessageDTO = new AbstractESMessageDTO();
            abstractESMessageDTO.setPathId(data.getPathId());
            abstractESMessageDTO.setBizId(String.valueOf(data.getBizId()));
            abstractESMessageDTO.setAuthor(data.getAuthor());
            abstractESMessageDTO.setType(data.getType());
            abstractESMessageDTO.setData(JsonUtil.toJsonString(data));
            abstractESMessageDTO.setCreateDate(new Date(data.getLastTime()));
            communityElasticSearchService.sync(abstractESMessageDTO);
        } else if (data.getEvent() == ESEventEnum.DELETE) {
            communityElasticSearchService.deleteDocument(data.getType(), String.valueOf(data.getBizId()));
        }
    }
}
